package com.labofjet.message.util;

import com.labofjet.common.service.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class MessageIdUtils {

	private static final String senderSnKeyPrefix = "message:sender:sn:"; // redis key prefix
	private static final String senderValuePrefix = "MSG-SENDER-"; // 返回的sn的prefix

	@Autowired
	private RedisService redisService;

	/**
	 * 生成message sender的sn
	 *
	 * @return
	 */
	public String generateMessageSenderSn() {
		String yyyyMMdd = DateFormatUtils.format(new Date(), "yyyyMMdd");
		String keyPrefix = senderSnKeyPrefix + yyyyMMdd;
		Long l = redisService.incr(keyPrefix);
		if (l == 1) {
			redisService.expire(keyPrefix, TimeUnit.DAYS.toSeconds(1)); // 1天后过期
		}
		String number = StringUtils.leftPad(l.toString(), 10, "0"); // 10 位
		return senderValuePrefix + yyyyMMdd + "-" + number; // MSG-SENDER-yyyyMMdd-0000000001
	}


}

